package com.zoran.study.spring.controller;


import com.zoran.study.spring.model.LoginUser;
import com.zoran.study.spring.model.request.CreditOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * UserController
 *
 * @author zouxm
 * @date 2018/6/22
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class LoginUserController {


    @RequestMapping("/test01")
    public LoginUser test01(@RequestAttribute("foo") String foo) {
        log.info("foo: {}", foo);
        return new LoginUser(1L, "zouxm", 20);
    }

    /**
     * @param name
     * @param userId
     * @RequestAttribute 接收filter中request设置的值
     */
    @RequestMapping(value = "/test02")
    public void test02(@RequestParam String name, @RequestAttribute("userId") String userId) {
        log.info("name: {},userId {}", name, userId);
    }


    @RequestMapping(value = "/test03", method = RequestMethod.POST)
    public CreditOrder test03(@Valid @RequestBody CreditOrder creditOrder) {
        log.info("credit order {}", creditOrder);
        return creditOrder;
    }

    @RequestMapping(value = "/test_fd", method = RequestMethod.POST)
    public CreditOrder testfd() {
        CreditOrder order=new CreditOrder();
        order.setEffectiveTime(new Date());
        return order;
    }

    @RequestMapping(value = "/test04")
    public void test04(HttpServletRequest request, @DateTimeFormat(pattern = "yyyy/MM/dd") Date date) {
        System.out.println(Arrays.toString(request.getParameterValues("name")));
        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println(date);
        log.info(request.getSession().getId());
    }

    @RequestMapping(value = "/test05",method = RequestMethod.GET)
    public void test05() {
        String str = null;
        System.out.println(str.toLowerCase());
    }

    @RequestMapping(value = "/test06",method = RequestMethod.GET)
    public void test06(@RequestParam("name") String name) {
        log.info("name : {}",name);
    }

    @RequestMapping("/download")
    public void download(HttpServletResponse res) throws IOException, URISyntaxException {
//        this.writeFileResponse("test.txt","hello world,邹小明".getBytes(),res);
        byte[] bytes = Files.readAllBytes(Paths.get(new URI("file:/Users/zouxiaoming/Desktop/111")));
        this.writeFileResponse("test.txt",bytes,res);
    }

    @RequestMapping("/upload")
    public void fileUpload(HttpServletRequest request, @RequestPart("uploadFile") MultipartFile uploadFile,@RequestParam("name") String name) throws IOException, URISyntaxException {
        log.info(uploadFile.getContentType());
        log.info(uploadFile.getOriginalFilename());
        log.info("name:{}",name);
//        Files.copy(uploadFile.getInputStream(),Paths.get(new URI("file:/Users/zouxiaoming/Desktop/file_temp/222")));
    }

    @RequestMapping("/uploads")
    public void fileUploads(HttpServletRequest request, @RequestPart("uploadFile") MultipartFile[] uploadFiles,@RequestParam("name") String name) throws IOException, URISyntaxException {
        for (MultipartFile uploadFile : uploadFiles) {
            log.info(uploadFile.getContentType());
            log.info(uploadFile.getOriginalFilename());
        }
        log.info("name:{}",name);
//        Files.copy(uploadFile.getInputStream(),Paths.get(new URI("file:/Users/zouxiaoming/Desktop/file_temp/222")));
    }

    private void writeFileResponse(String fileName, byte[] fileBytes, HttpServletResponse response)
            throws IOException {
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader(headerKey, headerValue);
        OutputStream os = response.getOutputStream();
        os.write(fileBytes, 0, fileBytes.length);
        int length = fileBytes.length;
        response.setContentLength(length);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    }


    @ModelAttribute
    public void beforeInvokingHandlerMethod(HttpServletRequest request) {
        request.setAttribute("foo", "hello");
    }

}
